package com.txunda.zhuohired.aty.user.home;

import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;

import com.ants.theantsgo.gson.GsonUtil;
import com.ants.theantsgo.tools.AlertDialog;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.lidroid.xutils.view.annotation.event.OnClick;
import com.txunda.zhuohired.R;
import com.txunda.zhuohired.adapter.user.home.SearchHistoryAdapter;
import com.txunda.zhuohired.base.BaseAty;
import com.txunda.zhuohired.bean.search.CommodityBean;
import com.txunda.zhuohired.bean.user.home.HotBean;
import com.txunda.zhuohired.http.pst.MemberHomePst;
import com.txunda.zhuohired.view.TagCloudView;

import org.litepal.crud.DataSupport;
import org.litepal.tablemanager.Connector;

import java.util.ArrayList;
import java.util.List;

/**
 * 创建人： Txd_Cjh
 * 创建时间： 2018/2/27 15:40
 * 功能描述：搜索页
 * 联系方式：jiahuanchen@126.com
 */

public class SearchAty extends BaseAty {
    /**
     * TagCloudView
     */
    @ViewInject(R.id.tag_search)
    private TagCloudView tag_search;
    /**
     * listView
     */
    @ViewInject(R.id.lv_search)
    private ListView lv_search;
    /**
     * editText
     */
    @ViewInject(R.id.et_search_head)
    private EditText et_search_head;

    private SearchHistoryAdapter searchHistoryAdapter;
    private List<CommodityBean> historyList;

    private List<HotBean.DataBean> hotList;

    private String selectContent = "";//搜索内容
    private MemberHomePst memberHomePst;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        showStatusBar(R.id.layout_search_head);
    }

    @Override
    @OnClick({R.id.tv_search_delete, R.id.tv_search_head})
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.tv_search_delete://删除历史搜索
                if (historyList.size() != 0) {
                    new AlertDialog(this).builder().setTitle("提示").setMsg("确认清空历史记录？")
                            .setPositiveButton("确认", new View.OnClickListener() {

                                @Override
                                public void onClick(View v) {
                                    // TODO Auto-generated method stub
                                    DataSupport.deleteAll(CommodityBean.class);
                                    initDb();
                                }
                            }).setNegativeButton("取消", new View.OnClickListener() {

                        @Override
                        public void onClick(View v) {
                            // TODO Auto-generated method stub

                        }
                    }).show();
                } else {
                    showErrorTip("没有可删除的历史记录~");
                }
                break;
            case R.id.tv_search_head://搜索
                ((InputMethodManager) getSystemService(INPUT_METHOD_SERVICE))
                        .hideSoftInputFromWindow(SearchAty.this.getCurrentFocus().getWindowToken(),
                                InputMethodManager.HIDE_NOT_ALWAYS);
                selectContent = et_search_head.getText().toString().trim();//搜索的内容
                //                    if (!TextUtils.isEmpty(selectContent)) {
                addDb();
                Bundle bundle = new Bundle();
                bundle.putString("select_content", selectContent);
                startActivity(JobListAty.class, bundle);
                finish();
                //                    } else {
                //                        showErrorTip("请输入搜索内容");
                //                    }
                break;
        }
    }

    @Override
    protected int getLayoutResId() {
        return R.layout.aty_search;
    }

    @Override
    protected void initialized() {
        memberHomePst = new MemberHomePst(this);
        historyList = new ArrayList<>();
        hotList = new ArrayList<>();
    }

    @Override
    protected void requestData() {
        memberHomePst.search();
        et_search_head.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                //按下了右下角的搜索,扫描枪测试actionId为0
                //输入法显示的时候，actionId=3，就是右下角的按钮的id
                if (actionId == EditorInfo.IME_ACTION_SEARCH || actionId == 0) {
                    // 先隐藏键盘
                    ((InputMethodManager) getSystemService(INPUT_METHOD_SERVICE))
                            .hideSoftInputFromWindow(SearchAty.this.getCurrentFocus().getWindowToken(),
                                    InputMethodManager.HIDE_NOT_ALWAYS);
                    selectContent = et_search_head.getText().toString().trim();//搜索的内容
                    //                    if (!TextUtils.isEmpty(selectContent)) {
                    addDb();
                    Bundle bundle = new Bundle();
                    bundle.putString("select_content", selectContent);
                    startActivity(JobListAty.class, bundle);
                    finish();
                    //                    } else {
                    //                        showErrorTip("请输入搜索内容");
                    //                    }
                }
                return true;
            }
        });

        initHistoryAdapter();

    }

    @Override
    public void onResume() {
        super.onResume();
        et_search_head.setFocusable(true);
        et_search_head.setFocusableInTouchMode(true);
        et_search_head.requestFocus();
        SearchAty.this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
        initDb();
    }

    /**
     * 数据库
     */
    private void initDb() {
        /**
         * 创建数据库
         */
        SQLiteDatabase db = Connector.getDatabase();// 创建数据库

        /**
         * 查询数据库
         */
        historyList = DataSupport.findAll(CommodityBean.class);
        for (CommodityBean commodity : historyList) {
            //            Log.e("===========", "====" + commodity.getCommodityName());
        }
        initHistoryAdapter();
    }

    /**
     * 增加数据库
     */
    private void addDb() {
        int state = 1;//1 不存在 2 存在
        historyList = DataSupport.findAll(CommodityBean.class);//查询到所有数据
        for (CommodityBean book : historyList) {
            if (selectContent.equals(book.getCommodityName())) {
                state = 2;
            }
        }
        if (state == 1) {
            //把数据库保存到Commodity表
            if (!TextUtils.isEmpty(selectContent)) {
                CommodityBean mCommodity = new CommodityBean();
                mCommodity.setCommodityName(selectContent);
                mCommodity.save();
            }
        }
    }

    /**
     * 历史记录adapter
     */
    private void initHistoryAdapter() {
        searchHistoryAdapter = new SearchHistoryAdapter(this, historyList);
        lv_search.setAdapter(searchHistoryAdapter);
        lv_search.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                selectContent = historyList.get(i).getCommodityName().toString().trim();
                addDb();
                Bundle bundle = new Bundle();
                bundle.putString("select_content", selectContent);
                startActivity(JobListAty.class, bundle);
                finish();
            }
        });
    }

    @Override
    public void onComplete(String requestUrl, String jsonStr) {
        super.onComplete(requestUrl, jsonStr);
        if (requestUrl.contains("search")) {
            //            L.e("==========search==========", jsonStr);
            HotBean hotBean = GsonUtil.GsonToBean(jsonStr, HotBean.class);
            hotList = hotBean.getData();
            List<String> hot = new ArrayList<>();
            for (int i = 0; i < hotList.size(); i++) {
                if (!TextUtils.isEmpty(hotList.get(i).getSearch_text())) {
                    hot.add(hotList.get(i).getSearch_text());
                }
            }
            tag_search.setTags(hot);
            tag_search.setOnTagClickListener(new TagCloudView.OnTagClickListener() {
                @Override
                public void onTagClick(int position) {
                    selectContent = hotList.get(position).getSearch_text().toString().trim();
                    addDb();
                    Bundle bundle = new Bundle();
                    bundle.putString("select_content", selectContent);
                    startActivity(JobListAty.class, bundle);
                    finish();
                }
            });

            return;
        }
    }
}
